package base;

import java.util.*;

import javax.servlet.http.*;

/**
 * @author qsj
 * 
 */
public class PageList {
	public PageList() {
	}

	/**
	 * 分页form请求的url
	 */
	public String url = "";

	/**
	 * 分页请求的表单FORM名
	 */
	public String FormName = "report";

	/**
	 * 系统生成的分页表单FORM内容
	 */
	public String FormString = "";

	/**
	 * 是否打印
	 */
	public boolean ifprint = false;

	/**
	 * 打印请求的url文件名
	 */
	public String printurl = "";

	/**
	 * 系统生成的导航按钮内容
	 */
	public String ButtonString = "";

	private String endButtonString = "";// 页尾分页按钮

	/**
	 * 当前显示的页码
	 */
	public int CurPage = 1;

	/**
	 * 总页数
	 */
	public int PageNum = 1;

	private int recoderNum = 0;// 总的记录条数

	private int onePage = 10;// 每页显示的记录数 为0不分页

	private int fromRs = 0;

	private java.sql.ResultSet rs;

	private String sqlNum;

	private String sqlList;

	private String sql;// 从第几条记录开始显示

	private String defaultOrder = null;// 默认排序方向

	private boolean endForm = false;// 是否输出页尾分页按钮

	private boolean ifpage = true;// 是否分页

	private String group = "";//

	/**
	 * 提交方法
	 */
	public String FormMethod = "post";

	public String getFormMethod() {
		return FormMethod;
	}

	public void setFormMethod(String formMethod) {
		FormMethod = formMethod;
	}

	public void setGroup(String group) {
		this.group = group;
	}

	/**
	 * 是否输出页尾分页按钮
	 * 
	 * @param ifEnd
	 */
	public void setEndForm(boolean ifEnd) {
		this.endForm = ifEnd;
	}

	/**
	 * 是否分页
	 * 
	 * @param ifpage
	 */
	public void setIfpage(boolean ifpage) {
		this.ifpage = ifpage;
	}

	/**
	 * 得到总的记录条数
	 * 
	 * @return
	 */
	public int getRecoderNum() {
		return this.recoderNum;
	}

	/**
	 * 页尾分页按钮
	 * 
	 * @return
	 */
	public String getEndButtonString() {
		return this.endButtonString;
	}

	public boolean Do(HttpServletRequest request) {
		try {
			if (url.trim().length() <= 0)
				url = request.getRequestURI();
			MakeForm(request);
			if (ifprint)
				if (printurl.trim().length() <= 0)
					return false;
			MakeButton();
		} catch (Exception ee) {
			return false;
		}
		return true;
	}

	// 生成POST方法的FORM
	private void MakeForm(HttpServletRequest request) throws Exception {
		FormString = "";
		FormString += "<form name=" + FormName + " method=" + FormMethod
				+ " action=" + url + ">";
		Enumeration<?> e = request.getParameterNames();
		while (e.hasMoreElements()) {
			String tmpname = e.nextElement().toString().trim();
			if (tmpname.equals("CurPage"))
				CurPage = Integer
						.parseInt((request.getParameter(tmpname) != null ? request
								.getParameter(tmpname)
								: "1"));
			else if (!tmpname.equals("totalRecordNum")) {
				for (int i = 0; i < request.getParameterValues(tmpname).length; i++)
					if (request.getParameterValues(tmpname)[i] != null)
						FormString += "<input type=hidden name=\"" + tmpname
								+ "\" value=\""
								+ (request.getParameterValues(tmpname)[i])
								+ "\"/>";
					else
						FormString += "<input type=hidden name=\"" + tmpname
								+ "\" value=\""
								+ request.getParameterValues(tmpname)[i]
								+ "\"/>";
			}
		}
		FormString += "<input type=hidden name=\"CurPage\" value=\"" + CurPage
				+ "\"/>";// totalRecordNum
		FormString += "<input type=hidden name=\"totalRecordNum\" value=\""
				+ recoderNum + "\"/>";
		FormString += "<input type=hidden name=\"pageturn\" value=\"true\"/>";
		FormString += "</form>";
	}

	private void MakeButton()
	// 输出系统导航按钮
	{
		ButtonString = "<table width='90%'  id=af_page><tr>";
		if (ifprint) {
			ButtonString += "<td><a href='javascript:" + FormName
					+ ".CurPage.value=" + CurPage + ";" + FormName + ".action="
					+ printurl + ";" + FormName + ".submit();'>打印</a></td>";
		}
		ButtonString += "<td width='27%'>共"
				+ PageNum
				+ "页  第"
				+ CurPage
				+ "页</td>  <td width='73%'><table border='0' cellpadding='0' cellspacing='0'><tr><td>";
		// 页数文本框

		// 首页按钮输出
		if (CurPage > 1)
			ButtonString += "<td><a href='javascript:" + FormName
					+ ".CurPage.value=1;" + FormName
					+ ".submit();'><span >首页</span></a></td>";
		else
			ButtonString += "<td><span class='gray1'>首页</span></td>";
		// ///前一页按钮输出
		if (CurPage > 1)
			ButtonString += "<td>&nbsp;&nbsp;<a href='javascript:" + FormName
					+ ".CurPage.value=" + (CurPage - 1) + ";" + FormName
					+ ".submit();'><span >上一页</span></a>&nbsp;&nbsp;</td>";
		else
			ButtonString += "<td>&nbsp;&nbsp;<span class='gray1'>上一页</span>&nbsp;&nbsp;</td>";

		// ///下一页按钮输出
		if (CurPage < PageNum)
			ButtonString += "<td><a href='javascript:" + FormName
					+ ".CurPage.value=" + (CurPage + 1) + ";" + FormName
					+ ".submit();'>下一页</a>&nbsp;&nbsp;</td>";
		else
			ButtonString += "<td>下一页&nbsp;&nbsp;</td>";
		// ///尾页按钮输出
		if (CurPage < PageNum)
			ButtonString += "<td><a href='javascript:" + FormName
					+ ".CurPage.value=" + PageNum + ";" + FormName
					+ ".submit();'>尾页</a>&nbsp;&nbsp;</td>";
		else
			ButtonString += "<td>尾页&nbsp;&nbsp;</td>";
		// 如果不是只有一页时，则输出跳至第几页
		if (PageNum != 1 && PageNum != 0) {
			ButtonString += "<script language='javascript'>";
			ButtonString += "function go_onkeydown(v)";
			ButtonString += "{";
			ButtonString += "if(event.keyCode==13)";
			ButtonString += "{";
			ButtonString += "go(v)";
			ButtonString += "}";
			ButtonString += "}";

			ButtonString += "function go(v){";
			ButtonString += "if (isNaN(v)||v.indexOf(\".\")>0)";
			ButtonString += "{ ";
			ButtonString += "alert(\"请输入正确的数字页号!\");jump.focus();";
			ButtonString += "}else{";
			ButtonString += "if(v>0 && v<=" + PageNum + "){";
			ButtonString += "report.CurPage.value=v;report.submit();}";
			ButtonString += "else{alert(\"请输入正确的数字页号!\");jump.focus();}";
			ButtonString += "}";
			ButtonString += "}";
			ButtonString += "</script>";
			ButtonString += "<td> 第<input type='text' size=2  name='jump' onkeydown='return go_onkeydown(this.value)' class=ipt2>页 <input type=button value='跳至' LANGUAGE=javascript onclick=\"return go(jump.value)\" class=ipt1></td>";

		}
		ButtonString += "</tr></table></td></tr></table> ";
		// ///输出页尾分页按钮
		if (endForm) {
			endButtonString = "<table width='90%' id=af_page><tr>";
			if (ifprint) {
				endButtonString += "<td><a href='javascript:" + FormName
						+ ".CurPage.value=" + CurPage + ";" + FormName
						+ ".action=" + printurl + ";" + FormName
						+ ".submit();'>打印</a></td>";
			}
			endButtonString += "<td width='27%'>共"
					+ PageNum
					+ "页  第"
					+ CurPage
					+ "页</td> <td width='73%'><table border='0' cellpadding='0' cellspacing='0'><tr><td>";
			// 页数文本框

			// 首页按钮输出
			if (CurPage > 1)
				endButtonString += "<td><a href='javascript:" + FormName
						+ ".CurPage.value=1;" + FormName
						+ ".submit();'><span >首页</span></a></td>";
			else
				endButtonString += "<td><span class='gray1'>首页</span></td>";
			// ///前一页按钮输出
			if (CurPage > 1)
				endButtonString += "<td>&nbsp;&nbsp;<a href='javascript:"
						+ FormName + ".CurPage.value=" + (CurPage - 1) + ";"
						+ FormName
						+ ".submit();'><span >上一页</span></a>&nbsp;&nbsp;</td>";
			else
				endButtonString += "<td>&nbsp;&nbsp;<span class='gray1'>上一页</span>&nbsp;&nbsp;</td>";

			// ///下一页按钮输出
			if (CurPage < PageNum)
				endButtonString += "<td><a href='javascript:" + FormName
						+ ".CurPage.value=" + (CurPage + 1) + ";" + FormName
						+ ".submit();'>下一页</a>&nbsp;&nbsp;</td>";
			else
				endButtonString += "<td>下一页&nbsp;&nbsp;</td>";
			// ///尾页按钮输出
			if (CurPage < PageNum)
				endButtonString += "<td><a href='javascript:" + FormName
						+ ".CurPage.value=" + PageNum + ";" + FormName
						+ ".submit();'>尾页</a>&nbsp;&nbsp;</td>";
			else
				endButtonString += "<td>尾页&nbsp;&nbsp;</td>";
			if (PageNum != 1 && PageNum != 0) {
				endButtonString += "<script language='javascript'>";
				endButtonString += "function go_onkeydown_end(v)";
				endButtonString += "{";
				endButtonString += "if(event.keyCode==13)";
				endButtonString += "{";
				endButtonString += "go_end(v)";
				endButtonString += "}";
				endButtonString += "}";

				endButtonString += "function go_end(v){";
				endButtonString += "if (isNaN(v)||v.indexOf(\".\")>0)";
				endButtonString += "{ ";
				endButtonString += "alert(\"请输入正确的数字页号!\");jumpEnd.focus();";
				endButtonString += "}else{";
				endButtonString += "if(v>0 && v<=" + PageNum + "){";
				endButtonString += "report.CurPage.value=v;report.submit();}";
				endButtonString += "else{alert(\"请输入正确的数字页号!\");jumpEnd.focus();}";
				endButtonString += "}";
				endButtonString += "}";
				endButtonString += "</script>";

				endButtonString += "<td> 第<input type='text' size=3  name='jumpEnd' onkeydown='return go_onkeydown(this.value)' class=ipt2>页 <input type=button value='跳至' LANGUAGE=javascript onclick=\"return go(jumpEnd.value)\" class=ipt1></td>";
			}

			endButtonString += "</tr></table></td></tr></table>";

		}
	}

	/**
	 * form提交表单 和 前置按钮导航
	 * 
	 * @return
	 * @author shm注
	 */
	public String getContent() {
		return FormString + ButtonString;
	}

	public int getPageNum() {
		return PageNum;
	}

	public String getCurPage() {// 080129
		return String.valueOf(CurPage);
	}

	public void setPageNum(int PageNum) {
		this.PageNum = PageNum;
	}

	public int getOnePage() {
		return onePage;
	}

	/**
	 * 设定一页中显示的条目数
	 * 
	 * @param onePage
	 */
	public void setOnePage(int onePage) {
		this.onePage = onePage;
	}

	public int getFromRs() {
		return fromRs;
	}

	public void setFromRs(int fromRs) {
		this.fromRs = fromRs;
	}

	public java.sql.ResultSet getRs() {
		return rs;
	}

	public void setRs(java.sql.ResultSet rs) {
		this.rs = rs;
	}

	public String getSqlNum() {
		return sqlNum;
	}

	public void setSqlNum(String sqlNum) {
		this.sqlNum = sqlNum;
	}

	public String getSqlList() {
		return sqlList;
	}

	public void setSqlList(String sqlList) {
		this.sqlList = sqlList;
	}

	public void setDefaultOrder(String defaultOrder) {
		this.defaultOrder = defaultOrder;
	}

	public String getDefaultOrder() {
		return defaultOrder;
	}

	public String getSqlCount(String sql) {
		// 注意。
		String sqlStr = sql.toUpperCase();
		if (group.equals("")) {
			if (sqlStr.indexOf("ORDER") > 0
					&& (sqlStr.indexOf("ORDER") > sqlStr.lastIndexOf(")"))) {
				sql = "select count(*) as NUM "
						+ sql.substring(sqlStr.indexOf("FROM"), sqlStr
								.indexOf("ORDER"));
			} else {
				sql = "select count(*) as NUM "
						+ sql.substring(sqlStr.indexOf("FROM"));
			}
		} else {
			if (sqlStr.indexOf("ORDER") > 0
					&& (sqlStr.indexOf("ORDER") > sqlStr.lastIndexOf(")"))) {
				sql = "select count(*) as NUM " + "FROM ("
						+ sql.substring(0, sqlStr.indexOf("ORDER"))
						+ " group by " + group + ") as a";
			} else {
				sql = "select count(*) as NUM FROM (" + sql + " group by "
						+ group + ") as a";
			}
		}
		return sql;
	}

	public String getSql() {
		return sql;
	}

	public void setSql(String sql) {
		this.sql = sql;
	}

	public ArrayList<HashMap<String, String>> getList(Power power, String sql)
			throws Exception {
		if (this.ifpage)
			sqlList = getPageNums(power, sql);
		else
			sqlList = getLimitSql(sql);
		ArrayList<HashMap<String, String>> list1 = power
				.getListFromSql(sqlList);
		return list1;
	}

	// 返回用于分页的sql,和设置记录总数,用于高级分页

	public String getPageNums(Power power, String sql) throws Exception {

		// 设置查询结果总条数
		if (!power.getParameter("totalRecordNum").equals(""))
			recoderNum = Integer.parseInt(power.getParameter("totalRecordNum"));// 根据参数设置（不是第一次执行时，会有此参数）
		else {
			sqlNum = getSqlCount(sql);
			HashMap<String, String> map = power.getMapFromSql(sqlNum);
			recoderNum = Integer.parseInt(map.get("NUM").toString());// 查询数据库进行设置（第一次执行）
		}
		// 生成总共的页数
		if (recoderNum % getOnePage() > 0) {
			setPageNum(recoderNum / getOnePage() + 1);
		} else {
			setPageNum(recoderNum / getOnePage());
		}
		Do(power.getRequest()); // 生成翻页脚本
		setFromRs((CurPage - 1) * getOnePage());// 设置查询记录的起始位置，注意：此方法必须在执行完生成翻页脚本的方法之后执行

		String order = "";

		if (defaultOrder != null && defaultOrder.length() > 0) {
			order = " order by " + defaultOrder;
		}
		if (group.length() > 0) {
			sql = sql + " group by " + group + " ";
		}
		sqlList = sql + order;
		if (onePage > 0) {
			sqlList += " limit " + getFromRs() + "," + onePage;
		}
		// ArrayList list1=power.getListFromSql(sqlList);
		return sqlList;
	}

	public String getLimitSql(String sqlC) {
		String sql = "";
		sql = sqlC + " Limit 0," + onePage;
		return sql;
	}

	/**
	 * 获得一些导航参数参数，包括curPage-当前页码，pageNum-页码数，nextURL-下一页链接，previousURL-上一页链接
	 * 
	 * @return HashMap
	 * @author shm
	 */
	public HashMap<String, Object> getNavigationPara() {
		HashMap<String, Object> para = new HashMap<String, Object>();
		para.put("curPage", String.valueOf(CurPage));
		para.put("pageNum", String.valueOf(PageNum));

		// 前一页按钮输出
		String previousURL = "";
		if (CurPage > 1)
			previousURL += "javascript:document.forms['" + FormName
					+ "'].CurPage.value=" + (CurPage - 1) + ";document.forms['"
					+ FormName + "'].submit();";
		else
			previousURL += "#";
		// 下一页按钮输出
		String nextURL = "";
		if (CurPage < PageNum)
			nextURL += "javascript:document.forms['" + FormName
					+ "'].CurPage.value=" + (CurPage + 1) + ";document.forms['"
					+ FormName + "'].submit();";
		else
			nextURL += "#";
		para.put("nextURL", nextURL);
		para.put("previousURL", previousURL);
		return para;
	}

}
